package com.huanke.iot.manage.service.device.operate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huanke.iot.base.dao.device.DeviceMapper;
import com.huanke.iot.base.dao.device.DeviceUpdateMapper;
import com.huanke.iot.base.po.device.DevicePo;
import com.huanke.iot.base.po.device.DeviceUpdatePo;
import com.huanke.iot.manage.service.gateway.MqttSendService;
import com.huanke.iot.manage.service.user.UserService;
import com.huanke.iot.manage.vo.request.device.operate.DeviceUpdateVersionRequest;
import com.huanke.iot.manage.vo.response.device.operate.DeviceUpdateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.UUID;


@Repository
@Slf4j
public class DeviceUpdateService {
    @Autowired
    private DeviceUpdateMapper deviceUpdateMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MqttSendService mqttSendService;
    @Autowired
    private DeviceMapper deviceMapper;


    /**
     * 查设备更新文件列表
     * @param deviceId
     * @return
     */
    public DeviceUpdateVo queryUpdateList(Integer deviceId) {
        DeviceUpdatePo deviceUpdatePo = deviceUpdateMapper.selectByDeviceId(deviceId);
        if(deviceUpdatePo == null){
            return null;
        }
        DeviceUpdateVo deviceUpdateVo = new DeviceUpdateVo();
        deviceUpdateVo.setDeviceId(deviceUpdatePo.getDeviceId());
        deviceUpdateVo.setVersion(deviceUpdatePo.getVersion());
        //处理文件
        String file = deviceUpdatePo.getFile();
        List<DeviceUpdateVo.File> files = JSONArray.parseArray(file, DeviceUpdateVo.File.class);
        deviceUpdateVo.setFileList(files);
        return deviceUpdateVo;
    }

    /**
     * 保存设备更新文件
     * @param request
     * @return
     */
    public Boolean save(DeviceUpdateVersionRequest request) {
        DeviceUpdatePo deviceUpdatePo = deviceUpdateMapper.selectByDeviceId(request.getDeviceId());
        if(deviceUpdatePo == null){
            deviceUpdatePo = new DeviceUpdatePo();
            deviceUpdatePo.setDeviceId(request.getDeviceId());
            deviceUpdatePo.setVersion(request.getVersion());
            deviceUpdatePo.setCreateTime(System.currentTimeMillis());
            deviceUpdatePo.setCreateUser(userService.getCurrentUser().getId());
            //处理文件
            String fileString = JSONObject.toJSONString(request.getFileList());
            deviceUpdatePo.setFile(fileString);
            return deviceUpdateMapper.insert(deviceUpdatePo) > 0;
        }else{
            deviceUpdatePo.setVersion(request.getVersion());
            //处理文件
            String fileString = JSONObject.toJSONString(request.getFileList());
            deviceUpdatePo.setFile(fileString);
            return deviceUpdateMapper.updateById(deviceUpdatePo) > 0;
        }
    }

    /**
     * 向设备推送更新设备指令
     * @param deviceId
     * @return
     */
    public String pushUpdateFile(Integer deviceId) {
        DeviceUpdatePo deviceUpdatePo = deviceUpdateMapper.selectByDeviceId(deviceId);
        JSONObject jsonObject = new JSONObject();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        jsonObject.put("msg_id", uuid);
        jsonObject.put("version", deviceUpdatePo.getVersion());
        List<DeviceUpdateVo.File> files = JSONArray.parseArray(deviceUpdatePo.getFile(), DeviceUpdateVo.File.class);
        JSONArray fileArray = new JSONArray();
        for (DeviceUpdateVo.File file : files) {
            fileArray.add(file.getFile());
        }
        jsonObject.put("files", fileArray);
        /*操作日志*/
        mqttSendService.sendMessage("/down2/grade/" + deviceId, jsonObject.toJSONString());
        return uuid;
    }


    /**
     * 查 向设备推送更新设备指令 结果
     * @param uuid
     * @return
     */
    public Boolean queryUpdateResult(String uuid) {
        String result = stringRedisTemplate.opsForValue().get("sendFunc." + uuid);
        if(result.equals("ok")){
            return true;
        }
        return null;
    }

    /**
     * 设备主动查询升级信息
     * @param mac
     * @return
     */
    public String verifyVersion(String mac) {
        DevicePo devicePo = deviceMapper.selectByMac(mac);
        Integer deviceId = devicePo.getId();
        DeviceUpdatePo deviceUpdatePo = deviceUpdateMapper.selectByDeviceId(deviceId);
        JSONObject jo = new JSONObject();
        jo.put("version", deviceUpdatePo.getVersion());
        List<DeviceUpdateVo.File> files = JSONArray.parseArray(deviceUpdatePo.getFile(), DeviceUpdateVo.File.class);
        JSONArray fileArray = new JSONArray();
        for (DeviceUpdateVo.File file : files) {
            if(file.getIsPush() == 1){
                fileArray.add(file.getFile());
            }
        }
        jo.put("files", fileArray);
        return jo.toJSONString();
    }
}
